import { Location, MapLength } from "../info/Predefine";

const { ccclass, property } = cc._decorator;

const list = [3, 6, 7, 4];
/**
 * 地形管理
 */
@ccclass
export default class TerrainManager extends cc.Component {
    bg: cc.TiledLayer;
    fog: cc.TiledLayer;
    bgFog: cc.TiledLayer;

    public static instance: TerrainManager;

    onLoad() {
        TerrainManager.instance = this;
        let mapComp = this.getComponent(cc.TiledMap);
        mapComp.enableCulling(false);
        this.bg = mapComp.getLayer("bg");
        this.fog = mapComp.getLayer("fog");
        this.bgFog = mapComp.getLayer("bgFog");
    }

    /**
     * 地图指定的位置改成地盘图块
     * @param location 
     */
    setLocationDomain(location: Location, gid: number = 1) { 
        this.bg.setTileGIDAt(gid, location.locationX, location.locationY);
    }

    /**
     * 受到轰炸，地面凹陷
     */
    bombardment(location: Location) {
        let gid = this.bg.getTileGIDAt(location.locationX, location.locationY)
        if (gid == 1) return;
        let gidIndex = list.findIndex(i => i == gid);
        if (gidIndex < list.length - 1) {
            gidIndex++;
            this.setLocationDomain(location, list[gidIndex]);
        }
    }

    /**
     * 清除指定矩形位置的迷雾
     * @param leftUp 
     * @param rightDown 
     */
    public clearRectFog(leftUp: Location, rightDown: Location) {
        this.hideSquareRegion(this.fog, leftUp, rightDown);
        leftUp.locationX -= 1; leftUp.locationY -= 1;
        rightDown.locationX += 1; rightDown.locationY += 1;
        this.hideSquareRegion(this.bgFog, leftUp, rightDown);
    }

    /**
     * 将地块设置为可见
     * @param fog 
     * @param location 
     * @returns 是否成功修改
     */
    setLocationView(fog: cc.TiledLayer, location: Location): boolean {
        let change = fog.getTileGIDAt(location.locationX, location.locationY) != 0;
        fog.setTileGIDAt(0, location.locationX, location.locationY);
        return change;
    }

    /**
     * 当前位置是否隐藏
     * @param location 
     * @returns 
     */
    isHide(location: Location) {
        if (!this.fog.node.active) {
            return false;
        }
        return this.fog.getTileGIDAt(location.locationX, location.locationY) > 0;
    }

    /**
     * 隐藏一块矩形区域的迷雾
     * @param fog 
     * @param leftUp 
     * @param rightDown 
     */
    private hideSquareRegion(fog: cc.TiledLayer, leftUp: Location, rightDown: Location) {
        let gridSize = MapLength;
        const startX = Math.max(leftUp.locationX, 0);
        const endX = Math.min(rightDown.locationX, gridSize - 1);
        const startY = Math.max(leftUp.locationY, 0);
        const endY = Math.min(rightDown.locationY, gridSize - 1);

        for (let x = startX; x <= endX; x++) {
            for (let y = startY; y <= endY; y++) {
                fog.setTileGIDAt(0, x, y); // 0 表示空 tile
            }
        }
    }

    protected onDestroy(): void {
        TerrainManager.instance = null;
    }

}
